<!--
  工作流选人组件，包括意见填写

  用法：
    <qm-workflow-select-user
      v-model="visible"
      :url="selectUserUrl"
      :params="models"
      :needChoose="needChoose"
      @select-done="doSend"
      @cancel="visible = false"
    ></qm-workflow-select-user>

  说明：
    v-model：绑定一个boolean值，控制弹窗的显示和隐藏
    url：选人的接口地址，取后台工作流控制器的getWorkflowViewModel 接口返回的urls.selectUser数据
    params：选人接口的参数，一般取this.models.model
    needChoose：是否需要选人，默认false，只填写意见
    @select-done：选完人之后触发该事件，传一Object参数：
      {
        choices: choices,                   // 选择的人
        selectComment: this.selectComment,  // 选择的意见，没太大意义
        sendComment: this.sendComment,      // 处理意见
      }
    doSend方法参考：
      doSend({ choices, selectComment, sendComment }) {
        if (this.controlData.workflow.needChoose) {
          if (choices.length == 0) {
            this.$message.warning("请选择处理人！");
            return;
          }
          if (choices.length > 1) {
            this.$message.warning("只能选择一个处理环节！");
            return;
          }
        }
        if (!sendComment) {
          this.$message.warning("请填写处理意见！");
          return;
        }
      }

    @cancel：点取消按钮触发该事件，取消之后要做什么

-->
<template>
  <vxe-modal
    class="qm-workflow-select-user"
    ref="selectUserModal"
    v-model="visible"
    :resize="true"
    :loading="loading"
    width="800px"
    height="450px"
    title="事项处理"
    destroy-on-close
    @close="close"
  >
    <el-form class="qm-workflow-select-user-form">
      <el-row :gutter="12">
        <el-col :span="9" v-if="needChoose">
          <el-tree
            style="height: 320px; overflow-y: auto"
            :data="treeData"
            v-if="visible"
            show-checkbox
            default-expand-all
            node-key="id"
            ref="qmWorkflowSelectUserTree"
            highlight-current
            :props="{
              children: 'children',
              label: 'text',
            }"
          ></el-tree>
        </el-col>
        <el-col :span="needChoose ? 15 : 24">
          <div>
            <el-select
              clearable
              v-model="selectComment"
              placeholder="选择我的常用意见"
              @change="onSelectComment"
            >
              <el-option
                v-for="item in commentOptions"
                :key="item.commentId"
                :label="item.content"
                :value="item.content"
              >
                <span style="float: left">{{ item.content }}</span>
                <span
                  v-if="item.userId != null"
                  style="float: right; color: #8492a6; font-size: 13px"
                >
                  <el-button
                    type="danger"
                    icon="el-icon-delete"
                    circle
                    @click="deleteComent(item.commentId)"
                  ></el-button>
                </span>
              </el-option>
            </el-select>
            <!-- <el-button type="text">设置常用意见</el-button> -->
          </div>
          <el-row>
            <el-col :span="2" :offset="10">
              <el-popover placement="top" width="400" trigger="click">
                <el-input
                  type="textarea"
                  v-model="content"
                  :autosize="{ minRows: 1, maxRows: 4}"
                  placeholder="请输入内容"
                ></el-input>
                <el-button
                  @click="submitContent"
                  type="primary"
                  icon="el-icon-plus"
                  size="mini"
                  style="margin-top: 10px;"
                >添加</el-button>
                <el-button type="text" slot="reference">添加我的常用意见</el-button>
              </el-popover>
            </el-col>
          </el-row>
          <div>
            <el-input
              type="textarea"
              :rows="11"
              placeholder="请填写您的意见"
              maxlength="200"
              :show-word-limit="true"
              v-model="sendComment"
            ></el-input>
          </div>
        </el-col>
      </el-row>
      <el-row style="text-align: right; margin-top: 16px">
        <el-button type="primary" @click="selectDone('qmWorkflowSelectUserTree')">确 定</el-button>
        <el-button @click="close">取消</el-button>
      </el-row>
    </el-form>
  </vxe-modal>
</template>

<script>
import _ from "lodash";
import request from "@/utils/request";

export default {
  name: "qm-workflow-select-user",
  props: {
    value: Boolean,
    needChoose: Boolean,
    url: String,
    params: Object,
    pageAction: String,
  },
  data() {
    return {
      visible: false,
      loading: false,
      treeData: [],
      commentOptions: [],
      selectComment: "",
      sendComment: "",
      content: "",
    };
  },
  watch: {
    value(visible) {
      if (visible && this.url) {
        this.fetchTreeData();
      } else {
        this.visible = visible;
      }
    },
  },
  methods: {
    deleteComent(val) {
      if (val == "") {
        this.$message.warning("删除失败");
        return;
      }
      request({
        url: "/workflow/actExtCommonComment/deleteContent",
        method: "post",
        data: {
          commentId: val,
        },
      })
        .then((r) => {
          this.fetchTreeData();
          this.selectComment = "";
          this.sendComment = "";
          this.$message.success("删除成功！");
        })
        .catch((e) => {
          reject(e);
        });
    },
    submitContent() {
      if (this.content == "") {
        this.$message.warning("不能设置空的意见喔");
        return;
      }
      request({
        url: "/workflow/actExtCommonComment/saveContent",
        method: "post",
        data: {
          content: this.content,
        },
      })
        .then((r) => {
          this.content = "";
          this.fetchTreeData();
          this.$message.success("添加成功！");
        })
        .catch((e) => {
          reject(e);
        });
    },
    close() {
      this.$emit("cancel");
      this.$emit("input", false);
    },
    selectDone(treeName) {
      let choices = [];
      if (this.needChoose) {
        choices = this.getSelectedUsers(treeName) || [];
      }
      this.$emit("select-done", {
        choices: choices,
        selectComment: this.selectComment,
        sendComment: this.sendComment,
      });
    },
    getSelectedUsers(treeName) {
      let selectedUsers = [];
      let choice = {
        tran: "",
        activity: "",
        users: [],
      };
      this.$refs[treeName].getCheckedNodes().forEach((item) => {
        if (item.type === "user") {
          // let tranNode = this.treeData[0];
          let tranNode = _.find(this.treeData, (i) => {
            return item.id.includes(i.id);
          });
          let activity = tranNode.data.activityId;
          let tran = tranNode.id;

          let find = _.find(selectedUsers, (u) => {
            return u.activity === activity;
          });
          if (!find) {
            find = _.extend({}, choice, { activity: activity, tran: tran });
            selectedUsers.push(find);
          }
          let idx = item.id.indexOf("$");
          find.users.push(idx > -1 ? item.id.substr(idx + 1) : item.id);
        }
      });
      selectedUsers.forEach((u) => {
        u.users = u.users.join(",");
      });
      return selectedUsers;
    },

    onSelectComment(val) {
      this.sendComment = val;
    },
    fetchTreeData() {
      this.visible = true;
      this.loading = true;

      this.getRequestPromise("/workflow/actExtCommonComment/loadMyComment", {})
        .then((r) => {
          this.commentOptions = r || [];
          if (this.needChoose) {
            return this.getRequestPromise(this.url, {
              ...{},
              ...this.params,
              ...{ pageAction: this.pageAction },
            });
          } else {
            return Promise.resolve();
          }
        })
        .then((r) => {
          if (this.needChoose) {
            this.treeData = this._buildChoices(r);
          }
          this.loading = false;
        });
    },
    _buildChoices(source) {
      let _this = this;
      let result = [];
      _.forEach(source, function (t, i) {
        // if (t.type == "dept") {
        //   _.forEach(t.children || [], function (t2, i2) {
        //     result.push(t2);
        //   });
        // } else {
        //   t.children = _this._buildChoices(t.children || []);
        //   result.push(t);
        // }
        t.children = _this._buildChoices(t.children || []);
        result.push(t);
      });
      return result;
    },
    getRequestPromise(url, params) {
      return new Promise((rs, rj) => {
        request({
          url: url,
          method: "post",
          data: params,
        })
          .then((rlt) => {
            rs(rlt);
          })
          .catch((rlt) => {
            rlt.message = "获取数据失败，请稍后重试";
            rj(rlt);
          });
      });
    },
  },
};
</script>

<style scoped>
.qm-workflow-select-user-form {
  padding: 12px 12px 0 12px;
}
</style>
